//
//  MTPanelChart.m
//  MTPanelChart
//
//  Created by Coollang on 16/7/19.
//  Copyright © 2016年 Coollang. All rights reserved.
//

#import "MTPanelChart.h"
#import "PNChart.h"

#define angleToArc(angle) (angle *M_PI/180)
#define GKProgressCenter CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5)


@interface MTPanelChart ()

@property(nonatomic, strong) UIBezierPath *progressPath;

@property (nonatomic, strong) CAShapeLayer *progressLayer;


@property (nonatomic, strong) CAShapeLayer *circleLayer;

/** 表针 */
@property (nonatomic, strong) CALayer *watchNeedle;
@property (nonatomic, assign)CGFloat progress;

/** 渐变色块 */
@property (nonatomic, strong) CAGradientLayer *gradientLayer;

@end
@implementation MTPanelChart

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
       
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self setUpShapeLayer];
    [self setPanelLayer];
    [self setProgressLayer];
    [self setPanelWatchNeedleLayer];
    
}

- (void)setProgressLayer {
    CGFloat minWH = MIN(self.bounds.size.width, self.bounds.size.height) * 0.5;
    self.progressPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(minWH, minWH) radius:self.radius startAngle:self.startAngle endAngle:self.endAngle clockwise:YES];
    
    
    self.circleLayer = [CAShapeLayer layer];
    self.circleLayer.frame = self.bounds;
    self.circleLayer.fillColor = [[UIColor clearColor] CGColor];
    self.circleLayer.strokeColor = self.stokeColor.CGColor;
    self.circleLayer.opacity = 0.5;
    self.circleLayer.lineWidth = self.borderWidth;
    self.circleLayer.path = self.progressPath.CGPath;
    [self.layer addSublayer:self.circleLayer];
    
    self.progressLayer = [CAShapeLayer layer];
    self.progressLayer.frame = self.bounds;
    self.progressLayer.fillColor =  [[UIColor clearColor] CGColor];
    self.progressLayer.strokeColor  = [[UIColor whiteColor] CGColor];
    self.progressLayer.lineWidth = self.borderWidth;
    self.progressLayer.path = self.progressPath.CGPath;
    self.progressLayer.strokeEnd = 0;
    [self.circleLayer setMask:self.progressLayer];
    
    if (self.progressLayer != nil) {
        [self.progressLayer removeFromSuperlayer];
    }
    
    CAShapeLayer *progressLayer = [[CAShapeLayer alloc]init];
    
    progressLayer.fillColor = [UIColor clearColor].CGColor;
    progressLayer.frame = self.bounds;
    self.progressLayer = progressLayer;
    self.progressLayer.strokeColor = kOrangeColor.CGColor;
    
    progressLayer.lineWidth = self.borderWidth;
    self.progressLayer.path = self.progressPath.CGPath;
    
    self.progressLayer.strokeEnd = 0.0;
    
    
    CALayer *gradientLayer = [CALayer layer];
    
    CAGradientLayer *gradientLayer1 =  [CAGradientLayer layer];
    gradientLayer1.frame = CGRectMake(0, 0, self.bounds.size.width, (self.bounds.size.height * 0.75));
    gradientLayer1.colors = @[(__bridge id)[UIColor colorWithHex:0xffd246].CGColor, (__bridge id)[UIColor colorWithHex:0xf8296b].CGColor];
    
//   [gradientLayer1 setLocations:@[@0.5,@1 ]];
    [gradientLayer1 setStartPoint:CGPointMake(0, 1)];
    [gradientLayer1 setEndPoint:CGPointMake(1, 1)];
    [gradientLayer addSublayer:gradientLayer1];
    self.gradientLayer = gradientLayer1;

    [gradientLayer setMask:progressLayer]; //用progressLayer来截取渐变层
    [self.layer addSublayer:gradientLayer];
}

- (void)updateProgress:(CGFloat)startProgress endProgress:(CGFloat)endProgress {

    self.progress = startProgress;
    CGFloat totalAngle = self.endAngle - self.startAngle;
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 1;
    pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pathAnimation.fromValue = @(startProgress);
    pathAnimation.toValue = @(endProgress);
    pathAnimation.fillMode = kCAFillModeForwards;
    pathAnimation.removedOnCompletion = NO;
    pathAnimation.autoreverses = NO;
    
    [self.progressLayer addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
    
    CABasicAnimation *needleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    needleAnimation.duration = 1;
    needleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    needleAnimation.fromValue = @(self.endAngle - self.startAngle + startProgress * totalAngle);
    needleAnimation.toValue = @(self.endAngle - self.startAngle + endProgress * totalAngle);
    needleAnimation.fillMode = kCAFillModeForwards;
    needleAnimation.removedOnCompletion = NO;
    needleAnimation.autoreverses = NO;
    
    [self.watchNeedle addAnimation:needleAnimation forKey:@"rotationAnimation"];
}


- (void)setUpShapeLayer {
    
    CAShapeLayer *circleLayer = [CAShapeLayer layer];
    // 指定frame，只是为了设置宽度和高度
    circleLayer.frame = self.bounds;
    // 设置填充颜色
    circleLayer.fillColor = [UIColor clearColor].CGColor;
    // 设置线宽
    circleLayer.lineWidth = self.borderWidth;
    // 设置线的颜色
    circleLayer.strokeColor =  self.stokeColor.CGColor;//[UIColor redColor].CGColor;
    
    // 使用UIBezierPath创建路径
    CGFloat minWH = MIN(self.bounds.size.width, self.bounds.size.height) * 0.5;
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(minWH, minWH) radius:self.radius startAngle:self.startAngle endAngle:self.endAngle clockwise:YES];
    // 设置CAShapeLayer与UIBezierPath关联
    circleLayer.path = circlePath.CGPath;
    // 将CAShaperLayer放到某个层上显示
    [self.layer addSublayer:circleLayer];
   
}

- (void)setPanelLayer {
    
    if (self.tickStrs.count > 0 && self.isShowTick) {
        
        // 计算并绘制刻度
        CGFloat totalAngle = ABS((self.endAngle - self.startAngle));
        
        CGFloat angleSpan = totalAngle / (self.tickStrs.count - 1);
        
        CGFloat minWH = MIN(self.bounds.size.width, self.bounds.size.height) * 0.5;
        
        CGFloat lineArc = 0.5;
        
        for (NSInteger i = 0; i < self.tickStrs.count; i++) {
            
            NSString *textString = self.tickStrs[i].stringValue;
            CGFloat angle = self.startAngle  + (angleSpan * i);
            
            CAShapeLayer *lineLayer = [CAShapeLayer layer];
            
            lineLayer.frame = CGRectMake(0, 0, 1, 3);
            CGFloat endAngle = angle + angleToArc(lineArc);
            if (i == self.tickStrs.count - lineArc) {
                angle = angle - angleToArc(lineArc);
                endAngle = self.endAngle;
            }
            
            UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(minWH, minWH) radius:self.radius - self.tickLineHeight - 3 startAngle:angle endAngle:endAngle clockwise:YES];
            lineLayer.lineWidth = self.tickLineHeight;
           
            lineLayer.strokeColor = [UIColor colorWithHex:0x8d8c90 alpha:0.5].CGColor;
            lineLayer.path = path.CGPath;
            [self.layer addSublayer:lineLayer];
            
            if (self.isShowtickString) {
                // 计算位置 -- 添加对应的文本
                 CGSize textSize = [self text:textString MaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:[UIFont systemFontOfSize:11]];
                
                CGFloat radius = self.radius + self.borderWidth + (sqrt(pow((textSize.width * 0.5), 2) + pow((textSize.height * 0.5), 2)) * 0.5);
                CGFloat lineLayerX = 0;
                CGFloat lineLayerY = 0;
                
               
                textSize = CGSizeMake(textSize.width, textSize.height);
                
                lineLayerX = cos(-angle) * radius;
                lineLayerY = sin(-angle) * radius;
            
                CATextLayer *textLayer = [CATextLayer layer];
                textLayer.string = textString;
                textLayer.font = (__bridge CFTypeRef _Nullable)([UIFont systemFontOfSize:11]);
                textLayer.bounds = CGRectMake(0, 0, textSize.width, textSize.height);
                textLayer.position = CGPointMake(self.bounds.size.width * 0.5 - lineLayerX, self.bounds.size.height * 0.5 - lineLayerY);
                textLayer.anchorPoint = CGPointMake(0.5, 0.5);
              
                textLayer.foregroundColor = self.tickStringBackGroundColor.CGColor;
                textLayer.contentsScale = [UIScreen mainScreen].scale;
                textLayer.fontSize = [UIFont systemFontOfSize:11].pointSize;
                [self.layer addSublayer:textLayer];
            }
            
        }
        
    }
    
}

// 添加表针
- (void)setPanelWatchNeedleLayer {
    
    if (self.watchNeedle != nil) {
        return;
    }
    
    CALayer *watchNeedle = [[CALayer alloc] init];
    self.watchNeedle = watchNeedle;
    UIImage *hourImage = [UIImage imageNamed:@"指针"];
    
    CGFloat height = self.radius - self.borderWidth - self.tickLineHeight;
    CGFloat width = hourImage.size.width;
    CGFloat scale = hourImage.size.width / hourImage.size.height; // 图片的宽高比
    
    width = scale * height;
    
    watchNeedle.bounds = CGRectMake(0, 0, width, height);
    
    watchNeedle.position = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);
    watchNeedle.anchorPoint = CGPointMake(0.5, 1);
    watchNeedle.contentsScale = [UIScreen mainScreen].scale;
    watchNeedle.contentsGravity = kCAGravityResizeAspect;
    watchNeedle.contents = (__bridge id _Nullable)(hourImage.CGImage);
    
    watchNeedle.transform = CATransform3DMakeRotation((self.endAngle - self.startAngle), 0, 0, 1);
    [self.layer addSublayer:watchNeedle];
}


// 计算文本的大小
- (CGSize)text:(NSString *)str MaxSize:(CGSize)maxSize font:(UIFont *)font {
    
    NSDictionary *attr = @{NSFontAttributeName : font};
    return [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
}

- (CGFloat)tickLineHeight {
    if (_tickLineHeight <= 0) {
        _tickLineHeight = 3;
    }
    return _tickLineHeight;
}

@end

